﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.Comm;
using DunSilverlight.ViewModel;

namespace DunSilverlight.Views
{
    public partial class CaseReturnStatistic : Page
    {
        ReportService.ReportServiceClient ser = new ReportService.ReportServiceClient();
        BankService.BankServiceClient bankSer = new BankService.BankServiceClient();
        UserService.UserServiceClient userSer = new UserService.UserServiceClient();
        public CaseReturnStatistic()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Report_CaseReturnStatistic))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent();

            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";
           
            bankSer.GetListByHQLCompleted += new EventHandler<BankService.GetListByHQLCompletedEventArgs>(bankSer_GetListByHQLCompleted);
            loadBank();

            userSer.GetListBySQLCompleted += new EventHandler<UserService.GetListBySQLCompletedEventArgs>(userSer_GetListBySQLCompleted);
            loadOper();

            ser.GetCaseReturnStatisticReportCompleted += new EventHandler<ReportService.GetCaseReturnStatisticReportCompletedEventArgs>(ser_GetCaseReturnStatisticReportCompleted);
        }

        /// <summary>
        /// 读取银行list
        /// </summary>
        private void loadBank()
        {
            bankSer.GetListByHQLAsync("From Company");
        }

        /// <summary>
        /// 读取操作员list（用权限判断）
        /// </summary>
        private void loadOper()
        {
            string orgNumber = AppGlobal.CurrentUser.Organization.FullNumber;
            string orgChildNumber = orgNumber + ".%";
            //获取当前机构下的操作员（具有催收权限）
            string sql = string.Format(
                        @" select u.Id,u.Name
                            from User_User as u 
                            left join User_Role as r on u.RoleId=r.Id
                            left join Organization_Organization org on u.OrganizationId = org.Id
                            where 
                                u.isused=1  and 
                                (org.FullNumber like '{0}' or org.FullNumber = '{1}') and 
                                exists(select 1 from User_Role_Right as rr 
                                            inner join User_Right as ur on rr.RightId=ur.Id 
                                        where ur.Number='process_case' and
                                rr.RoleId=r.Id) ", orgChildNumber, orgNumber);

            userSer.GetListBySQLAsync(sql);
        }
      
        IList<DunLibrary.Client.Company> bankList;
        void bankSer_GetListByHQLCompleted(object sender, BankService.GetListByHQLCompletedEventArgs e)
        {
            int total = 0;
            bankList = JsonSerializerHelper.JsonToEntities<DunLibrary.Client.Company>(e.Result, out total);
            //取出银行分类（非支行）
            cboxBank.ItemsSource = bankList;

        }

        void userSer_GetListBySQLCompleted(object sender, UserService.GetListBySQLCompletedEventArgs e)
        {
            int total = 0;
            var objList = JsonSerializerHelper.JsonToEntities<object[]>(e.Result, out total);
            List<UserModel> userList = objList.Select(c => new UserModel
            {
                Id = int.Parse(c[0].ToString()),
                Name = c[1].ToString()
            }).ToList();

            cboxOper.ItemsSource = userList;
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {

            if (timePeriod.SelectedDate == null)
            {
                Tools.ShowMessage("请选择数据期号!", "", false);
                return;
            }

            if (cboxOper.SelectedItem == null && !string.IsNullOrEmpty(cboxOper.Text))
            {
                Tools.ShowMessage("催收负责人输入错误!", "", false);
                return;
            }

            if (cboxBank.SelectedItem == null && !string.IsNullOrEmpty(cboxBank.Text))
            {
                Tools.ShowMessage("银行分类输入错误!", "", false);
                return;
            }


            DateTime selected = timePeriod.SelectedDate.Value;
            int period = int.Parse(selected.ToString("yyyyMM"));

            int? import = null;
            if (timeImport.SelectedDate != null)
                import = int.Parse(timeImport.SelectedDate.Value.ToString("yyyyMMdd"));

            int? operId = null;
            if(cboxOper.SelectedItem != null)
               operId = int.Parse(cboxOper.SelectedValue.ToString());

            string arrealDiffStart = null;
            if (delayStart.Value != null)
                arrealDiffStart = delayStart.Value.ToString();

            string arrealDiffEnd = null;
            if (delayEnd.Value != null)
                arrealDiffEnd = delayEnd.Value.ToString();

            double? arrealAmountStart = null;
            if (amountStart.Value != null)
            {
                double val = double.Parse(amountStart.Value.ToString());
                if (val > 0.0)
                    arrealAmountStart = val;
            }

            double? arrealAmountEnd = null;
            if (amountEnd.Value != null)
            {
                double val = double.Parse(amountEnd.Value.ToString());
                if (val > 0.0)
                    arrealAmountEnd = val;
            }

            if (arrealAmountStart != null && arrealAmountEnd != null)
            {
                if (arrealAmountEnd < arrealAmountStart)
                {
                    Tools.ShowMessage("‘欠费金额’输入错误!", "最大金额必须大于最小金额!", false);
                    amountStart.Value = amountEnd.Value = null;
                    amountStart.Focus();
                    return;
                }
            }


            int? bankId = null;
            if (cboxBank.SelectedItem != null)
                bankId = (cboxBank.SelectedItem as DunLibrary.Client.Company).Id;

            string orgNum = null;
            if (AppGlobal.CurrentUser.Organization != null)
                orgNum = AppGlobal.CurrentUser.Organization.FullNumber;
            Tools.ShowMask(true);
            ser.GetCaseReturnStatisticReportAsync(period,import, operId, arrealDiffStart, arrealDiffEnd,
                arrealAmountStart, arrealAmountEnd, bankId, orgNum);
          
        }


        void ser_GetCaseReturnStatisticReportCompleted(object sender, ReportService.GetCaseReturnStatisticReportCompletedEventArgs e)
        {
            int total = 0;
            var list = JsonSerializerHelper.JsonToEntities<DunLibrary.Report.CaseReturnStatistic>(e.Result, out total);
            RadGridView1.ItemsSource = list;
            Tools.ShowMask(false);
        }

        /// <summary>
        /// 重置所有查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            delayStart.Value = delayEnd.Value = null;
            
            amountStart.Value = amountEnd.Value = null;

            if (cboxOper.SelectedItem != null)
                cboxOper.SelectedItem = null;
            else
                cboxOper.Text = null;

            if (cboxBank.SelectedItem != null)
                cboxBank.SelectedItem = null;
            else
                cboxBank.Text = null;


            RadGridView1.ItemsSource = null;
        }

        

        private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnQuery_Click(sender, null);
            }
        }
    }
}
